package com.example.springsecuritydemo2.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.springsecuritydemo2.common.R;
import com.example.springsecuritydemo2.domain.User;
import com.example.springsecuritydemo2.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public R login(@RequestBody User user){
        String jwt = userService.login(user);
        if(StringUtils.hasLength(jwt)){
            return R.ok().message("登录成功").data("token", jwt);
        }else{
            return R.error().message("登录失败");
        }

    }

    /**
     * 用户退出
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/logOut")
    public R logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = request.getParameter("Authorization");
        //如果没有从头部获取token，那么从参数里面获取
        if (ObjectUtils.isEmpty(token)) {
            token = request.getHeader("Authorization");
        }
        //获取用户相关信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            //清空用户信息
            new SecurityContextLogoutHandler().logout(request, response, authentication);
            //清空redis里面的token
            System.out.println(stringRedisTemplate.opsForValue().get("token_" + token));
            stringRedisTemplate.delete("token_" + token);
        }
        return R.ok().message("用户退出成功");
    }
}
